﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using JT.WEB.Service;
using JTWEB3.Models.Request;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NewsPublish.Model.Entity;
using NewsPublish.Model.Request;
using NewsPublish.Model.Response;

namespace JTWEB3.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class NewsController : Controller
    {
        private readonly NewsService _newsService;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public NewsController(NewsService newsService, IWebHostEnvironment hostingEnvironment)
        {
            _newsService = newsService;
            _hostingEnvironment = hostingEnvironment;
        }
        // GET: News
        public ActionResult Index()
        {
            ResponseModel newsClassifys = _newsService.GetNewsClassifyList();
            return View(newsClassifys);
        }

        // GET News
        [HttpGet]
        public JsonResult GetNews(int pageIndex, int pageSize, int classifyId, string KeyWord)
        {
            List<Expression<Func<News, bool>>> wheres = new List<Expression<Func<News, bool>>>();
            if (classifyId > 0)
            {
                wheres.Add(c => c.NewsClassifyId == classifyId);
            }
            if (!string.IsNullOrEmpty(KeyWord))
            {
                wheres.Add(c => c.Title.Contains(KeyWord));

            }
            ResponseModel news = _newsService.NewsPageQuery(pageSize, pageIndex, out int total, wheres);
            return Json(new { total, news.data });
        }
        //NewsAdd
        public ActionResult NewsAdd()
        {
            ResponseModel newsClassifys = _newsService.GetNewsClassifyList();
            return View(newsClassifys);
        }
        [HttpPost]
        public async Task<JsonResult> AddNews(AddNews addNews, IFormCollection collection)
        {
            if (addNews is null || collection is null)
            {
                throw new ArgumentNullException(nameof(addNews));
            }



            if (addNews.NewsClassifyId <= 0 || string.IsNullOrEmpty(addNews.Title) || string.IsNullOrEmpty(addNews.Contents))
            {
                return Json(new ResponseModel { code = 0, result = "标题和正文不能为空！" });
            }
            IFormFileCollection files = collection.Files;
            if (files.Count > 0)
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                string relativeDirPath = "\\NewsPic";
                string absolutePath = webRootPath + relativeDirPath;
                string[] fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };//定义上传文件格式
                string extension = Path.GetExtension(files[0].FileName);
                if (fileTypes.Contains(extension))
                {
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);

                    }
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
                    string filePath = absolutePath + "\\" + fileName;
                    using (FileStream stream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(stream);

                    }
                    addNews.Image = "/NewsPic/" + fileName;
                    return Json(_newsService.AddNews(addNews));
                }
                return Json(new ResponseModel { code = 0, result = "图片格式有误" });

            }
            addNews.Image = "/NewsPic/news.svg";
            return Json(_newsService.AddNews(addNews));


        }
        public async Task<JsonResult> AddImg(IFormCollection collection)
        {
            if (collection is null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            IFormFileCollection files = collection.Files;
            if (files.Count > 0)
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                string relativeDirPath = "\\NewsPic";
                string absolutePath = webRootPath + relativeDirPath;
                string[] fileTypes = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };//定义上传文件格式
                string extension = Path.GetExtension(files[0].FileName);
                if (fileTypes.Contains(extension))
                {
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);

                    }
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
                    string filePath = absolutePath + "\\" + fileName;
                    using (FileStream stream = new FileStream(filePath, FileMode.Create))
                    {
                        await files[0].CopyToAsync(stream).ConfigureAwait(false);

                    }
                    string Image = $"/NewsPic/{fileName}";

                    return Json(new AddImg { errno = 0, result = Image, data = new string[] { Image } });

                }
                return Json(new ResponseModel { code = 0, result = "上传类型错误，.gif,.jpg, .jpeg, .png, .bmp" });
            }
            return Json(new ResponseModel { code = 0, result = "文件为空" });
        }
        //Delete News 
        public JsonResult DelNews(int id)
        {
            if (id < 0)
            {
                return Json(new ResponseModel { code = 0, result = "新闻不存在" });
            }
            return Json(_newsService.DelOneNews(id));
        }
        // GET: NewsClassify/Create
        public ActionResult NewsClassify()
        {
            ResponseModel newsClassifys = _newsService.GetNewsClassifyList();
            return View(newsClassifys);
        }
        public ActionResult NewsClassifyAdd()
        {
            return View();
        }

        [HttpPost]
        public JsonResult NewsClassifyAdd(AddNewsClassify addNewsClassify)
        {
            if (string.IsNullOrEmpty(addNewsClassify.Name))
            {
                return Json(new ResponseModel { code = 0, result = "请输入新闻类别名称" });
            }
            return Json(_newsService.AddNewsClassify(addNewsClassify));
        }

        public ActionResult NewsClassifyEdit(int Id)
        {
            return View(_newsService.GetOneNewsClassify(Id));
        }
        [HttpPost]
        public JsonResult NewsClassifyEdit(EditNewsClassify editNewsClassify)
        {
            if (string.IsNullOrEmpty(editNewsClassify.Name))
            {
                return Json(new ResponseModel { code = 0, result = "请输入新闻类别" });
            }
            return Json(_newsService.EditNewsClassify(editNewsClassify));
        }

    }
}